import { asyncRoutes, constantRoutes } from '@/router'
import store from '@/store'
import router from '@/router'
import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })
  // alert(res)
  // console.log(res)
  // debugger
  return res
}

// 遍历后台传来的路由字符串，转换为组件对象
export function filterAsyncRouter2(asyncRouterMap) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (router.component) {
      if (route.component === 'Layout') {
        try {
          route.component = Layout
        } catch (e) {
          alert(e.Message)
        }
      } else {
        route.component = import('@/views/icons/index') // _import(route.component) // 导入组件
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })

  // alert(accessedRouters)
  // debugger
  return accessedRouters
}

const state = {
  // systom:null,
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  // SET_SYSTOM: (state, s) => {
  //   state.systom = s
  // }
}

const actions = {
  generateRoutes({ commit }, roles) {
    // alert(22222222)
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }

      // const menus = filterAsyncRouter(store.getters.menus) // 1.过滤路由
      router.addRoutes(store.getters.menus) // 2.动态添加路由
      global.antRouter = store.getters.menus // 3.将路由数据传递给全局变量，做侧边栏菜单渲染工作
      accessedRoutes.concat(global.antRouter)

      // debugger
      commit('SET_ROUTES', global.antRouter)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
